#!/bin/env python

import os
from pytz import timezone, utc
from datetime import datetime as dt, timedelta
from gi.repository import GExiv2, GLib

VERSION = '1.3.3'

class Format:
    Date = '%Y:%m:%d'
    Time = '%H:%M:%S'
    DateTime = '%Y:%m:%d %H:%M:%S'
    GPSDate  = '%Y:%m:%d'
    GPSTime  = '%H/1 %M/1 %S/1'


class Image(GExiv2.Metadata):
    path = None
    def __init__(self, path):
        try:
            super().__init__(path)
            self.path = path
        except (IOError, GLib.GError) as err:
            raise IOError(path+': loading metadata failed\ '+ str(err))

        self.timestamp = self.get_gps_timestamp()
        if self.timestamp is None:
            for key in ['Exif.Image.DateTimeOriginal',
                        'Exif.Photo.DateTimeOriginal']: 
                try:
                    self.timestamp = dt.strptime(self[key], Format.DateTime)
                    self.utc_offset(self['Exif.Image.TimeZoneOffset'])
                    break
                except KeyError:
                    continue


    def save(self):
        self.save_file(self.path)


    def get_gps_timestamp(self):
        try:
            date = self['Exif.GPSInfo.GPSDateStamp']
            time = self['Exif.GPSInfo.GPSTimeStamp']
            fmt = Format.GPSDate + Format.GPSTime
            return dt.strptime(date + time, fmt).replace(tzinfo=utc)
        except KeyError:
            return None


    def get_gps_location(self):
        lng, lat, alt = self.get_gps_info()
        if not 'Exif.GPSInfo.GPSLatitude' in self:
            lat = None
        if not 'Exif.GPSInfo.GPSLongitude' in self:
            lng = None
        if not 'Exif.GPSInfo.GPSAltitude' in self:
            alt = None
        if lat is None and lng is None and alt is None:
            return None
        return (lat, lng, alt)


    def set_gps_timestamp(self, timestamp):
        timestamp = timestamp.astimezone(utc)
        self['Exif.GPSInfo.GPSDateStamp'] = timestamp.strftime(Format.GPSDate)
        self['Exif.GPSInfo.GPSTimeStamp'] = timestamp.strftime(Format.GPSTime)


    def set_gps_location(self, latitude, longitude, altitude):
        self.set_gps_info(longitude, latitude, altitude)


    def rename(self, newname):
        if newname == self.path:
            return True
        elif os.path.exists(newname):
            return False
        else:
            os.rename(self.path, newname)
            self.path = newname
            return True


    def utc_offset(self, offset):
        if not isinstance(offset, (timedelta)):
            offset = timedelta(minutes=float(offset))
        self.timestamp = (self.timestamp - offset).replace(tzinfo=utc)
        return offset


    def __str__(self):
        return self.path


if __name__ == '__main__':
    fn = Filename('tmp/5.jpg')    

    img = Image('tmp/1.jpg')
    img.utc_offset(5)
#    from glocation import Location
#    loc = Location.fromaddress('Copenhagen', timezone=True)
    
#    lat, lng = loc.coordinates()
#    print((lat, lng), loc.timezone())

#    img = Image('tmp.jpg')
#    print(img.get_gps_timestamp())
#    print(img.get_gps_location())

#    img.set_gps_location(lat, lng, 0.0)
#    img.set_gps_timestamp(img.timestamp)
#    print(img.get_gps_location())
    #img.save()
